package tjs.study.notes.dotest.jvm.heap;

import tjs.study.notes.dotest.TjsStudyNotesApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by Nicky.Tang on 2021/10/14 11:32 上午
 *
 * @since 02.12.10
 */
public class 测试流的close方法 {
    public static void main(String[] args) throws Exception {
//        new MyFileInputStream(new File(TjsStudyNotesApplication.work_space + "/jvm/heap/测试流的close方法.java"));
        // fileInputStream.close();//即使没有显示调用close方法，MyFileInputStream被回收时，会调用finalize，进而调用close方法
        newWrite();
        System.gc();
        Thread.currentThread().sleep(9999999);
    }

    public static void newWrite() {
        //try-with-resources （实现AutoCloseable接口即可）
        try (
                FileInputStream stream1 = new MyFileInputStream(new File(TjsStudyNotesApplication.work_space + "/jvm/heap/测试流的close方法.java"));
                FileInputStream stream2 = new MyFileInputStream(new File(TjsStudyNotesApplication.work_space + "/jvm/heap/测试流的close方法.java"))) {
            int i = 1 / 0;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //写一个新类，以便在可视化工具中更好的找到当前对象
    static class MyFileInputStream extends FileInputStream implements AutoCloseable {

        public MyFileInputStream(File file) throws FileNotFoundException {
            super(file);
        }

        @Override
        public void close() throws IOException {
            System.out.println("当前对象被回收，回调close方法");
            super.close();
        }
    }
}
